from aiohttp import web
import asyncio, json, aiohttp, logging, re
import mySecurity, account_manager, utility_classes
import data_apis, yydrm

routes = web.RouteTableDef()

@routes.post('/permission')
async def get_permission(request):
    data = await get_post_json(request, ['api_name'])
    if data:
        d = yydrm.get_drm_status(data['api_name'])
        return web.Response(text = str(d))
    else:
        res = utility_classes.ReturnTemplate(1, '调用失败')
    return web.json_response(res.__dict__)

@routes.post('/apis')
async def call_api(request):
    data = await get_post_json(request, ['token', 'api'])
    if data:
        token = data['token']
        api_name = data['api'].get('api_name')
        if api_name:
            code = account_manager.check_user(token, api_name)
            if code == 0:
                r = await data_apis.call_api(data['api']['api_name'], data['api']['args'])
                if r:
                    res = utility_classes.ReturnTemplate(0,data = {'token':account_manager.update_proof(token), 'data':r})
                    #return web.json_response(res.__dict__)
                else:
                    print('接口返回空')
            elif code == 1000:
                print('token验证失败')
                res = utility_classes.ReturnTemplate(1000, '调用失败。请重新登录。')
            elif code == 1001:
                res = utility_classes.ReturnTemplate(1001, '无权限。')
                print("无权限")
    else:
        res = utility_classes.ReturnTemplate(1, '调用失败')
    return web.json_response(res.__dict__)




@routes.post('/login')
async def login(request):
    data = await get_post_json(request, ['user_id', 'passwd'])
    if data:
        user_id = data['user_id']
        passwd = data['passwd']
        res = await account_manager.login(user_id, passwd)
    else:
        res = utility_classes.ReturnTemplate(3,'bad params.')
    return web.json_response(res.__dict__)

@routes.post('/logout')
async def logout(request):
    #先验证token在注销
    pass

@routes.post('/resetpasswd')
async def resetpasswd(request):
    data = await get_post_json(request, ['user_id', 'passwd', 'yzm'])
    if data:
        user_id = data['user_id']
        passwd = data['passwd']
        yzm = data['yzm']
        if mySecurity.check_yzm(user_id, yzm):
            res = await account_manager.resetpasswd(user_id, passwd)
        else:
            res = utility_classes.ReturnTemplate(2, '验证码错误。')
    else:
        res = utility_classes.ReturnTemplate(3,'bad params.')
    return web.json_response(res.__dict__)

@routes.post('/register')
async def register(request):
    '''
    需要参数：user_id, password, nickname, yzm
    返回code： 0成功，1验证码错误， 2账号已存在， 3传入参数错误
    '''
    data = await get_post_json(request, ['user_id', 'passwd', 'nickname', 'yzm'])
    if data:
        user_id = data.get('user_id')
        passwd = data.get('passwd')
        nickname = data.get('nickname')
        yzm = data.get('yzm')
        if mySecurity.check_yzm(user_id, yzm):
            if await account_manager.register(user_id, passwd, nickname):
                res = utility_classes.ReturnTemplate(0)
            else:
                res = utility_classes.ReturnTemplate(2,'用户已存在。')
        else:
            res = utility_classes.ReturnTemplate(1,'验证码错误。')
    else:
        res = utility_classes.ReturnTemplate(3,'bad params.')
    return web.json_response(res.__dict__)

@routes.post('/top_up')
async def top_up(request):
    data = await get_post_json(request,['user_id', 'card_key', 'yzm', 'friend_id'])
    if data:
        user_id = data['user_id']
        card_key = data['card_key']
        yzm = data['yzm']
        friend_id = data['friend_id']
        if mySecurity.check_yzm(user_id, yzm):
            res = await account_manager.top_up(user_id, card_key, friend_id)
        else:
            res = utility_classes.ReturnTemplate(3,'验证码不正确。.')
    else:
        res = utility_classes.ReturnTemplate(4,'bad params.')
    return web.json_response(res.__dict__)

@routes.post('/getuserpoint')
async def get_point(request):
    data = await get_post_json(request, ['token'])
    if data:
        token = data['token']
        if account_manager.check_user(token, '') == 0:
            d = await account_manager.get_user_point(token[0])
            res = utility_classes.ReturnTemplate(0,data = {'token':account_manager.update_proof(token), 'data':d})
        else:
            res = utility_classes.ReturnTemplate(1000, '调用失败。请重新登录。')
    else:
        res = utility_classes.ReturnTemplate(1, '调用失败')
    return web.json_response(res.__dict__)


@routes.get('/get_yzm/{phone}')
async def test_get_yzm(request):
    phone = request.match_info['phone']
    res = await mySecurity.test_send_yzm(phone)
    return web.Response(text = res)

@routes.post('/getyzm')
async def get_yzm(request):
    data = await get_post_json(request, ['phone'])
    if data:
        if await mySecurity.send_yzm(data['phone']):
            res = utility_classes.ReturnTemplate(0)
        else:
            res = utility_classes.ReturnTemplate(1, '发送失败。')
        return web.json_response(res.__dict__)



@routes.post('/create_cards')
async def create_cards(request):
    data = await get_post_json(request, ['token', 'num', 'face_amount'])
    if data:
        token = data['token']
        code = account_manager.check_user(token, 'create_cards')
        if code == 0:
            keys = await mySecurity.create_card_key(data['num'], data['face_amount'])
            if keys:
                res = utility_classes.ReturnTemplate(0,data = {'token':account_manager.update_proof(token), 'data':keys})
            else:
                print('接口返回空')
        elif code == 1000:
            print('token验证失败')
            res = utility_classes.ReturnTemplate(1000, '调用失败。请重新登录。')
        elif code == 1001:
            res = utility_classes.ReturnTemplate(1001, '无权限。')
            print("无权限")
    else:
        res = utility_classes.ReturnTemplate(1, '调用失败')
    return web.json_response(res.__dict__)

@routes.post('/root_top_up')
async def root_top_up(request):
    data = await get_post_json(request, ['token', 'user_id', 'friend_id', 'amount'])
    if data:
        code = account_manager.check_user(data['token'], 'create_cards')
        if code == 0:
            keys = await mySecurity.create_card_key(1, data['amount'])
            if keys:
                res = await account_manager.top_up(data['user_id'], keys[0][0], data['friend_id'])
            else:
                utility_classes.print_log("创建卡密接口返回空")
        elif code == 1000:
            utility_classes.print_log('跟用户充值token验证失败')
            res = utility_classes.ReturnTemplate(1000, '调用失败。请重新登录。')
        elif code == 1001:
            res = utility_classes.ReturnTemplate(1001, '无权限')
            utility_classes.print_log('无权限进行跟用户充值')
    else:
        res = utility_classes.ReturnTemplate(1, '调用失败')
    return web.json_response(res.__dict__)

async def get_post_json(request, keys = []):
    try:
        jo = await request.json()
        if not isinstance(jo, dict):
            jo = json.loads(jo)
        for k in keys:
            if k not in jo:
                print(k)
                return None
        return jo
    except json.decoder.JSONDecodeError as e:
        return None



async def init(loop):
    global client
    client = aiohttp.ClientSession(loop=loop)
    mySecurity.con = client
    data_apis.client = client
    app = web.Application()
    app.add_routes(routes)
    srv = await (loop.create_server(app.make_handler(), '127.0.0.1', 8800))
    return srv


def main():
    loop = asyncio.get_event_loop()
    tasks = [init(loop), mySecurity.monitor_yzm(), account_manager.settlement()]
    tasks.extend(data_apis.get_cron_tasks())
    loop.run_until_complete(asyncio.wait(tasks))
    loop.run_forever()


main()